<template>
  <div>
    <div class="pageTopTitle">渠道管理</div>
    <div class="app-container">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px"
               size="small"
      >
        <el-form-item label="渠道名称" prop="name">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入渠道名称"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="渠道类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择渠道类型" style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          </el-form-item>
        <el-form-item label="渠道编号" prop="code">
          <el-input
            v-model="queryParams.code"
            clearable
            placeholder="请输入渠道编号"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="app-container mt20">
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="channelList">
        <el-table-column label="渠道名称" prop="name"/>
        <el-table-column label="渠道编号" prop="code"/>
        <el-table-column label="渠道登陆账号" prop="account"/>
        <el-table-column label="渠道类型" prop="type">
          <template slot-scope="scope">
            <el-tag >{{ typeList.find(item => item.value === scope.row.type).label }}</el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column label="状态" prop="status">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span class="fs-12">{{ scope.row.status === 0 ? '待审核' : '审核通过' }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="渠道城市" prop="cityName"/>
        <el-table-column label="上级渠道" prop="parentName">
          <template slot-scope="scope">
            <span >{{ scope.row.parentChannel ? scope.row.parentChannel.name : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务经理" >
          <template slot-scope="scope">
            <span >{{ scope.row.businessUser ? scope.row.businessUser.nickName : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createAt" width="180"/>
        <el-table-column class-name="small-padding fixed-width" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />

      <!-- 添加或修改渠道对话框 -->
      <el-drawer
        :title="title"
        :visible.sync="open" :wrapper-closable="false"
        size="35%"
      >
        <div class="drawer-content">
          <el-form ref="form" :model="form" :rules="rules" label-width="98px">
            <el-form-item  prop="account">
               <span slot="label">
                <el-tooltip content="渠道账号是渠道登陆系统的账号，默认密码为123456。" placement="top">
                <i class="el-icon-question"></i>
               </el-tooltip>
               渠道账号
              </span>
              <el-input v-model="form.account" placeholder="请输入渠道账号"  :disabled="form.id" />
            </el-form-item>
            <el-form-item label="渠道名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入渠道名称"/>
            </el-form-item>
            <el-form-item label="渠道编号" prop="code">
              <el-input v-model="form.code" disabled placeholder="请输入渠道编号"/>
            </el-form-item>
            <el-form-item label="城市" prop="cityCode">
              <el-cascader
                v-model="selectedOptions"
                :options="options"
                filterable
                style="width: 100%;"
                @change="handleCityChange"
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="渠道类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择渠道类型" style="width: 100%;">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="上级渠道" prop="parentId">
              <el-select v-model="form.parentId" :remote-method="remoteParentMethod" filterable
                         placeholder="输入注册渠道名称可查询" remote style="width: 100%;"
              >
                <el-option v-for="item in parentList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="业务经理" prop="businessUserId">
              <el-select v-model="form.businessUserId" :remote-method="remoteBusinessMethod" filterable
                         placeholder="输入注册手机号可查询" remote style="width: 100%;"
              >
                <el-option v-for="item in businessList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
              </el-select>
            </el-form-item>
            <el-divider>
              <div class="fs-14 f-w-bold">渠道联系人信息</div>
            </el-divider>
            <div v-for="(contact, index) in form.contactList" :key="index" class="contact-info">
              <div class="contact-item-name">
                联系人{{ index + 1 }}
              </div>
              <div style="flex: 1;margin-right: 20px">
                <div style="display: flex;align-items: center;margin-bottom: 12px">
                  <el-col :span="8">
                    <el-input v-model="contact.name" placeholder="姓名" size="small"/>
                  </el-col>
                  <el-col :span="2" style="text-align: center">-</el-col>
                  <el-col :span="14">
                    <el-input v-model="contact.phone" maxlength="11" placeholder="手机号" size="small"/>
                  </el-col>
                </div>
                <div style="display: flex;align-items: center;margin-bottom: 12px;">
                  <el-col :span="8">
                    <el-input v-model="contact.job" placeholder="职位" size="small"/>
                  </el-col>
                  <el-col :span="2" style="text-align: center">-</el-col>
                  <el-col :span="14">
                    <el-input v-model="contact.company" maxlength="11" placeholder="公司名称" size="small"/>
                  </el-col>
                </div>
                <el-input v-model="contact.address" placeholder="公司地址" size="small"/>
              </div>
              <div class="btn-group">
                <i class="el-icon-circle-plus-outline" style="color: #165DFF; font-size: 22px; cursor: pointer;"
                   @click="addContact"
                ></i>
                <i v-if="index > 0" class="el-icon-remove-outline" style="margin-top: 22px;
                color: #F53F3F; font-size: 22px; cursor: pointer"
                   @click="removeContact(index)"
                ></i>
              </div>
            </div>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button size="small" style="width: 120px;" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" style="width: 120px;" @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { listChannel, getChannel, delChannel, addChannel, updateChannel } from '@/api/web/channel'
import { listUser } from '@/api/system/user'
import { provinceAndCityData, codeToText } from 'element-china-area-data'

export default {
  name: 'Channel',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 渠道表格数据
      channelList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        type: null,
        status: null
      },
      typeList: [
        { label: '机构', value: 1 },
        { label: '企业', value: 2 },
        { label: '个人', value: 3 },
        { label: '其他', value: 4 }
      ],
      options: provinceAndCityData,
      userList: [],
      parentList: [],
      businessList: [],
      selectedOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        account: [
          { required: true, message: '渠道账号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '渠道名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '渠道编号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询渠道列表 */
    getList() {
      this.loading = true
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        account: null,
        name: null,
        code: null,
        type: null,
        cityName: null,
        cityCode: null,
        provinceCode: null,
        parentId: null,
        businessUserId: null,
        contactList: [{
          name: null,
          phone: null,
          job: null,
          company: null,
          address: null
        }]
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    remoteMethod(e) {
      listUser({
        phonenumber: e
      }).then(response => {
        this.userList = response.rows
      })
    },
    /** 业务经理查询 */
    remoteBusinessMethod(e){
      listUser({
        phonenumber: e,
        roleId: 102
      }).then(response => {
        this.businessList = response.rows
      })
    },

    remoteParentMethod(e){
      listChannel({
        name: e,
      }).then(response => {
        this.parentList = response.rows
      })
    },

    addContact() {
      this.form.contactList.push({
        name: null,
        phone: null,
        job: null,
        company: null,
        address: null
      })
    },

    removeContact(index) {
      this.form.contactList.splice(index, 1)
    },

    handleCityChange(e) {
      this.form.cityCode = e[1]
      this.form.provinceCode = e[0]
      // 使用 map 方法将 selectedOptions 中的每个 code 转换为对应的文本
      const locationTexts = this.selectedOptions.map(code => codeToText[code])
      this.form.cityName = locationTexts.join('-')
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.selectedOptions = []
      this.parentList = []
      this.form.code = 'CH' + Math.floor(Math.random() * 1000)
      this.open = true
      this.title = '添加渠道'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getChannel(id).then(response => {
        this.form = {
          ...response.data,
          type: (Number)(response.data.type)
        }
        if(this.form.parentChannel){
          this.parentList = [this.form.parentChannel]
        }
        if(this.form.businessUser){
          this.businessList = [this.form.businessUser]
        }

        const provinceCode = this.form.provinceCode
        const cityCode = this.form.cityCode
        this.selectedOptions = [provinceCode, cityCode]
        this.form.cityName = codeToText[provinceCode] + '-' + codeToText[cityCode]
        this.open = true
        this.title = '修改渠道'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 判断联系人信息是否为空
          if (this.form.contactList.length === 0 || this.form.contactList.every(item => !item.name && !item.phone)) {
            this.$message.error('请至少添加一个联系人信息')
            return
          }

          if (this.form.id != null) {
            updateChannel(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addChannel(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除渠道编号为"' + ids + '"的数据项？').then(function() {
        return delChannel(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="scss" scoped>

.contact-info {
  display: flex;
  align-items: center;
  margin-bottom: 30px;

  .contact-item-name {
    // 文字竖直排列
    width: 20px;
    margin-right: 20px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #165DFF;
    color: #165DFF;
    padding: 12px 0;
  }

  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }
}

.drawer-content {
  padding: 0 30px 80px 20px;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  text-align: right;
  padding: 16px;
  width: 100%;
  border-top: 1px solid #eee;
  background-color: #fff;
}

::v-deep .el-form-item__label {
  font-weight: 500 !important;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0 0 4px 0 !important;
}

::v-deep .el-divider--horizontal {
  margin: 40px 0 !important;
}
</style>
